package com.cloud.gatewaySpringSecurity.handler;

import com.cloud.gatewaySpringSecurity.utils.SaveMessage;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * @author zhozixiong
 * @date 2023/03/02
 *
 * 登录失败处理器
 */
@Component
public class LoginFailureHandler implements ServerAuthenticationFailureHandler {

    @Override
    public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, AuthenticationException authentication) {
        ServerHttpResponse response = webFilterExchange.getExchange().getResponse();
        String error;
        if (authentication instanceof UsernameNotFoundException) {
            error = "用户不存在:";
        } else if (authentication instanceof BadCredentialsException) {
            error = "密码错误:";
        } else if (authentication instanceof LockedException) {
            error = "用户锁定";
        } else if (authentication instanceof AccountExpiredException) {
            error = "账户过期";
        } else if (authentication instanceof DisabledException) {
            error = "账户不可用:";
        } else {
            error = "系统错误:";
        }
        return SaveMessage.save(response, HttpStatus.UNAUTHORIZED, error + ":" + authentication.getMessage());
    }
}
